var util = require('../../utils/util')
var api = require('../../config/api.js');
const innerAudioContext = wx.createInnerAudioContext()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    task: {},
    imgListview:[],
    imgList: [],
    tasklog:{
      taskId:null,
      remark:null,
      fliePath:[]
    },
    taskLogList:[],
    loadModalSound: false,


    //------oss上传所需参数------//
    ossAccessKeyId: '',
    policy: '',
    signature: '',
    //上传图片地址
    imagePathUrl: ''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取oss上传参数
    this.oss();
    let that = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('row', function (data) {
      //获取任务详情
      that.getTaskById(data.taskId)
      //获取上报历史
      that.getLogByTaskId(data.taskId)
    })

  },

   //获取任务详情
   getTaskById(taskId) {
    let that = this
    let dataup = {
      taskId: taskId
    }
    util.request(api.queryTaskDetail, JSON.stringify(dataup), 'POST').then(function (res) {
      if (res.code == '200') {
        that.closeModal();
        that.setData({
          task: res.data
        })

      } else {
        util.showErrorToast(res.message);
        that.closeModal();
      }

    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });

  },
  
   //获取任务详情
   getLogByTaskId(taskId) {
    let that = this
    let dataup = {
      taskId: taskId
    }
    util.request(api.taskLogListById, JSON.stringify(dataup), 'POST').then(function (res) {
      console.log(res)
      if (res.code == '200') {
        that.closeModal();
        that.setData({
          taskLogList: res.data
        })

      } else {
        util.showErrorToast(res.message);
        that.closeModal();
      }

    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });

  },


    //隐患描述
    hiddenRemarkInput(event){
      this.data.tasklog.remark=event.detail.value
    },

//点击播放录音
gotoPlay: function (e) {
    var filePath = this.data.taskInfo.soundPath
    console.log("======" + filePath)
    if(filePath === null){
        wx.showToast({
            title: '没有现场录音',
            icon: 'success',
            duration: 1000
        })
        return
    }
    //点击开始播放
    let that = this
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.data.taskInfo.soundPath,
        innerAudioContext.onPlay(() => {
            console.log('开始播放')
            //speaking.call(that);
            that.setData({
                loadModalSound: true
            })
        });
    innerAudioContext.onEnded((res) => {
        console.log('播放停止' + res)
        that.setData({
            loadModalSound: false
        })
    });

    innerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
    })
},


 
//----------上传文件--------------------//

/**
   * 初始化参数
   */
  oss(){
    let that=this;
    //发起网络请求
    util.request(api.ossinit,null).then(function (res) {
      //console.log(res)  
          that.setData({
            policy:res.policy,
            ossAccessKeyId:res.ossAccessKeyId,
            signature:res.signature
          })
        }      
    ).catch((err) => {
      console.log("远程服务器catch:" + err);
      //reject(err);
    });
  },

//浏览图片
ViewImage(e) {
  wx.previewImage({
    urls: this.data.imgList,
    current: e.currentTarget.dataset.url
  });
},

//浏览图片
ViewImageView(e) {
  console.log(e)
    wx.previewImage({
      urls: e.currentTarget.dataset.data.fliePath,
      current: e.currentTarget.dataset.data.fliePath[0]
    });
  },

ChooseImage() {
  wx.chooseImage({
    count: 4, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album','camera'], //从相册选择
    success: (res) => {
      if (this.data.imgList.length != 0) {
        this.setData({
          imgList: this.data.imgList.concat(res.tempFilePaths)
        })
      } else {
        this.setData({
          imgList: res.tempFilePaths
        })
      }

  //上传
  console.log( res.tempFilePaths[0])
  this.uploadfile(res.tempFilePaths[0])



    }
  });
},

DelImg(e) {
  wx.showModal({
    title: '提示',
    content: '确定要删除吗？',
    cancelText: '取消',
    confirmText: '确定',
    success: res => {
      if (res.confirm) {
        this.data.imgList.splice(e.currentTarget.dataset.index, 1);
        this.data.tasklog.fliePath.splice(e.currentTarget.dataset.index, 1);
        this.setData({
          imgList: this.data.imgList,
          ['tasklog.fliePath']: this.data.tasklog.fliePath
        })
      }
    }
  })
},

/**
 * 上传文件
 */
uploadfile(tempFilePath){
    let that=this;
    const key = new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
    // 上传图片到oss
    wx.uploadFile({
      // 直传的oss地址
      url: 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com',
      // 上传的文件
      filePath: tempFilePath,
      // 必须为file
      name: 'file',
      // 表单数据
      formData: {
        // key：文件路径，如 user/666.png
        //直接 key: "${filename}" 是存放在根目录，文件名为上传的文件名
        // 如果后端签名时指定了dir则开头必须同后端的一致，如后端指定了 “user/” 开头则必须是 user/xxx.xx
        'key': key,
        // 自定义成功响应值 ，默认响应204
        'success_action_status': '200',
        'OssAccessKeyId': this.data.ossAccessKeyId,
        // 后端签名后发回的policy
        'policy': this.data.policy,
        // 后端返回的签名
        'signature': this.data.signature
      },
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          console.log("上传成功！")
         
        //   that.setData({
        //     imagePathUrl: 'https://yqyf.oss-cn-chengdu.aliyuncs.com/'+key,
        //     ['reportinfo.attchmentUrl']: 'https://yqyf.oss-cn-chengdu.aliyuncs.com/'+key
        //   })

        var pathTemp='https://hiddengwb.oss-cn-chengdu.aliyuncs.com/'+key;
        that.data.tasklog.fliePath.push(pathTemp);


        } else {
          console.log("上传失败！")
          console.log(res)
        }
      },
      fail(error) {
        console.log("上传错误")
        console.log(error)
      }
    })
  },

  //日志列表
  taskloglist() {
    wx.navigateTo({
      url: '/pages/tasklog/taskloglist?taskId=' + this.data.taskId
    })

  },
  //上报日志
  submittask() {
   
    //判断是否选择图片
    if(this.data.tasklog.fliePath<1){
      util.showErrorToast("请上传现场图片！");
      return
   }
   if(this.data.tasklog.remark==null || this.data.tasklog.remark=='' ){
    util.showErrorToast("请填写备注！");
    return
 }
   
  //提交上报数据
  this.data.tasklog.taskId=this.data.task.taskId;
  let dataup=this.data.tasklog;
  let that=this;
  console.log(JSON.stringify(dataup))
  that.loadModal();
  util.request(api.submitTaskLog,JSON.stringify(dataup),'POST').then(function (res) {
      console.log(res)
      if (res.code == 200) {
          that.closeModal();
          //刷新界面
          wx.navigateBack({})
      
      } else {
        util.showErrorToast(res.message);
      }
      
    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });

  },

  
//进度条
loadModal () {
  this.setData({
    loadModal: true
  })
},
closeModal (){
  this.setData({
    loadModal: false
  })
},

})